package com.iyohei.service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iyohei.entry.User;
import com.iyohei.mapper.UserMapper;

@Service
public class UserServiceImpl implements UserService{
	
	@Autowired
	UserMapper userDao;
	
	@Override
	public long deleteById(long id) {
		System.out.println("Before执行删除。。");
		long result = userDao.deleteById(id);
		int i = 10/0;
		System.out.println("After执行删除。。");
		return result;
	}
	
	public User getById(Long id) {
		return userDao.getById(id);
	}
	
	@Override
	public User getUserById(Long id) {
		/**
		 * 1.注册驱动
		 * 2.获取链接
		 * 3.获取操作对象
		 * 4.定义sql
		 * 5.执行sql
		 * 6.获取结果
		 * 7.关闭流操作
		 */
		
		try {
			//1.注册驱动
			System.err.println("************************");
			Class.forName("com.mysql.jdbc.Driver");
			//2.获取链接
			String url = "jdbc:mysql://localhost:3306/kevin";
			String userName = "root";
			String password = "123456";
			Connection conn = DriverManager.getConnection(url,userName,password);
			//3.获取操作对象
//			Statement statement = conn.createStatement();
			//4.定义sql
			String sql = "select * from user where id = " + id;
			PreparedStatement preState = conn.prepareStatement(sql);
			//5.执行sql
			ResultSet result = preState.executeQuery(sql);
			System.err.println("************************");
			//6.处理结果
			User user = new User();
			while (result.next()) {
				int userId =  result.getInt("id");
				System.out.println("userId:"+userId);
				String userName2 = result.getString("name");
				System.out.println("name:"+userName);
				int age = result.getInt("age");
				System.out.println("age:"+age);
				user.setId(userId);
				user.setUser(userName2);
				user.setAge(age);
			}
			//释放资源
			result.close();preState.close();conn.close();
			System.err.println("user:"+user);
			return user;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	


}
